import paramiko
from loguru import logger
from os import path

logger.add("ssh_remote_connetc.log", level="INFO", rotation="1 week", retention="10 days")


class Client():

    def __init__(self, hostname, username="sdc"):
        self.hostname = hostname
        self.username = username
        self.ssh_client = paramiko.SSHClient()   
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())   
        # 连接SSH服务端，以用户名和密码进行认证 ，调用connect方法连接服务器
        private = paramiko.RSAKey.from_private_key_file('/home/snail/.ssh/id_rsa') 
        self.ssh_client.connect(hostname=hostname, port=22, username=self.username, pkey=private)
        self.sftp_client = self.ssh_client.open_sftp()

    def exec_command(self, cmd):
        try:
            stdin, stdout, stderr = self.ssh_client.exec_command(cmd)
            out = stdout.read().decode('utf-8').strip()
            error = stderr.read().decode('utf-8').strip()
            if error:
                logger.error(error)
            return out
        except Exception as e:
            logger.error(e)
            raise e 

    def put(self,local_file, remote_path):
        # only put a regular file, not folder
        if path.isfile(local_file):
            try:
                self.sftp_client.put(local_file, remote_path)
                return "Successful ~"
            except Exception as e:
                logger.debug(e)
        else:
            logger.info("not a regular file, don't select folder")
            return "Failed: not a regular file, don't select folder"

    def close(self):
        try:
            self.ssh_client.close()
        except Exception as e:
            logger.error(e)
